﻿

using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Travel.CommonUtil.Snowflake;
using Travel.Data;
using Travel.Data.Dtos;
using Travel.Data.Entity;
using Travel.Data.Inputs;

namespace Travel.Service.User.Impl
{
    public class MenuModuleService : ServiceBase, IMenuModuleService
    {

        /// <summary>
        /// 根据菜单模块ID获取一条记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<MenuModuleDto>> GetMenuModuleById(long id)
        {
            var tabMenu = await TravelContext.TabMenuModules!.AsNoTracking().FirstOrDefaultAsync(c => !c.Deleted && c.Id == id);
            if (tabMenu == null)
            {
                return Results<MenuModuleDto>.FailResult("记录不存在");
            }
            var menuModuleDto = ObjectMapper.Map<MenuModuleDto>(tabMenu);
            menuModuleDto.ParentMenuModuleName = TravelContext.TabMenuModules.Find(tabMenu.ParentMenuModuleId)?.ModuleName;
            return Results<MenuModuleDto>.DataResult(menuModuleDto);
        }

        /// <summary>
        /// 菜单模块查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<PageDto<MenuModuleDto>>> MenuButtonQuery(MenuModuleQueryInput input)
        {
            var query = from p in TravelContext.TabMenuModules.AsNoTracking()
                        join t in TravelContext.TabMenuModules.AsNoTracking() on p.ParentMenuModuleId equals t.Id into grouping
                        from g in grouping.DefaultIfEmpty()
                        select new
                        {
                            p.Id,
                            p.ModuleName,
                            p.LinkUrl,
                            p.IconUrl,
                            p.ParentMenuModuleId,
                            ParentMenuModuleName = g.ModuleName,
                            UpdatedTime = p.UpdatedTime.Value
                        };
            if (input.ParentId.HasValue && input.ParentId.Value > 0)
            {
                query = query.Where(c => c.ParentMenuModuleId == input.ParentId);
            }
            if (!string.IsNullOrWhiteSpace(input.MenuName))
            {
                query = query.Where(c => c.ModuleName.Contains(input.MenuName));
            }
            PageDto<MenuModuleDto> result = new PageDto<MenuModuleDto>
            {
                Total = query.Count(),
            };
            var list = query.OrderByDescending(c => c.UpdatedTime).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).Select(c => new MenuModuleDto
            {
                Id = c.Id,
                ModuleName = c.ModuleName,
                LinkUrl = c.LinkUrl,
                IconUrl = c.IconUrl,
                ParentMenuModuleId = c.ParentMenuModuleId,
                ParentMenuModuleName = c.ParentMenuModuleName,
                UpdatedTime = c.UpdatedTime

            }).ToList();
            result.Data = list;
            return Results<PageDto<MenuModuleDto>>.DataResult(result);
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="loginUserId"></param>
        /// <param name="idList"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<int>> RemoveMenuModule(params long[] idList)
        {
            if (!idList.Any())
            {
                return Results<int>.FailResult("必须选择一条数据");
            }
            var entityList = TravelContext.TabMenuModules.Where(c => !c.Deleted && idList.Contains(c.Id));
            if (!entityList.Any())
            {
                return Results<int>.FailResult("数据不存在");
            }
            var menuIdList = entityList.Select(s => s.Id);
            //判断需要删除的模块中是否包含有子模块或者子菜单按钮，如果有，则不让删
            var count = TravelContext.TabMenuModules.Count(c => menuIdList.Contains(c.ParentMenuModuleId.Value) && !c.Deleted);
            if (count > 0)
            {
                return Results<int>.FailResult("当前要删除中的模块存在子模块");
            }
            count = TravelContext.TabMenuButtons.Count(c => !c.Deleted && menuIdList.Contains(c.MenuModuleId.Value));
            if (count > 0)
            {
                return Results<int>.FailResult("当前要删除的模块中存在子按钮");
            }
            await entityList.ForEachAsync(c =>
             {
                 c.UpdatedUserId = LoginUserId;
                 c.Deleted = true;
             });
            return Results<int>.DataResult(await TravelContext.SaveChangesAsync());
        }

        /// <summary>
        /// 添加或修改菜单模块
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Results<int>> UpdateOrAdd(MenuModuleInput input)
        {
            var count = TravelContext.TabMenuModules.Count(c => !c.Deleted && c.ModuleName == input.ModuleName && input.ParentMenuModuleId == c.ParentMenuModuleId);
            if (count > 0)
            {
                return Results<int>.FailResult("菜单也存在");
            }
            if (input.Id > 0)
            {
                var entity = await TravelContext.TabMenuModules.FindAsync(input.Id);
                ObjectMapper.Map(input, entity);
            }
            else
            {
                input.Id = SnowIdWorker.NextId();
                await TravelContext.TabMenuModules.AddAsync(ObjectMapper.Map<TabMenuModule>(input));
            }
            return Results<int>.DataResult(await TravelContext.SaveChangesAsync());
        }
    }
}
